package com.woniu.user.resolver;

import com.woniu.common.annotation.LoginUser;
import com.woniu.common.utils.JwtUtil;
import com.woniu.user.feignClient.UserFeignClient;
import com.woniu.user.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Title
 * @Author 武术有栖
 * @Description:
 */
@Component
public class LoginUserHandleArgumentResolver implements HandlerMethodArgumentResolver {

    @Lazy
    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(UserLoginVO.class) && methodParameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String token = nativeWebRequest.getHeader("token");
        String mobile = (String) JwtUtil.parseJWT(token).get("mobile");
        UserLoginVO userLoginVO = userFeignClient.getByMobile(mobile).getData();
        return userLoginVO;
    }
}
